package com.yaj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yaj.dto.UserDto;
import com.yaj.enums.BasicEnum;
import com.yaj.exception.BaseException;
import com.yaj.pojo.User;
import com.yaj.mapper.UserMapper;
import com.yaj.properties.JwtTokenManagerProperties;
import com.yaj.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yaj.utils.JwtUtil;
import com.yaj.utils.UserThreadLocal;
import com.yaj.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaojiu
 * @since 2024-08-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProp;

    @Override
    public UserVo login(UserDto dto) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, dto.getUsername());
        User user = baseMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(user)){
            throw new BaseException(BasicEnum.USER_NOT_EXIST);
        }
        if (!user.getPassword().equals(dto.getPassword())){
            throw new BaseException(BasicEnum.PASSWORD_ERROR);
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtTokenManagerProp.getBase64EncodedSecretKey(), jwtTokenManagerProp.getTtl(), claims);
        UserVo userVo = new UserVo();
        userVo.setToken(token);
        userVo.setUserInfo(user);
        return userVo;
    }
}
